from threading import Thread
from queue import Queue


class Logger(Thread):
    public_context = None
    log_path = ''
    logger_queue = Queue()
    read_type = ''

    def __init__(self, log_path='./log.txt', read_type='w'):
        Thread.__init__(self)
        self.logger_queue = Queue()
        self.log_path = log_path
        self.read_type = read_type
        self.public_context = None

    def run(self):
        print('Logger started.')
        log_file = open(self.log_path, self.read_type, encoding='utf-8')
        while True:
            content = self.logger_queue.get()
            if content == 'SYSTEM_EXIT':
                break
            log_file.write(content)
            log_file.write('\n')
            log_file.flush()
        log_file.close()
        print('Logger exit.')
        return 0

    def log_message(self, msg):
        self.logger_queue.put('{} -> {}'.format(self.public_context.get_current_time(), msg))

    def finish(self):
        self.logger_queue.put('SYSTEM_EXIT')







